import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import Message from "@/pulging/Message/js/Message.js"
import  {useRouter} from "vue-router"
export const useUserStore = defineStore("user", () => {
    const router = useRouter()
    const authorization = ref()
    const userInfo = ref() 
    const isLogin = ref(false)
    function setUserStore() {
       const token = localStorage.getItem("authorization")
       const user_Info = JSON.parse(localStorage.getItem("userInfo"))
       if (token && user_Info) {   //只有两个都有的时候才会 在store中存 authorization、userInfo与isLogin
            authorization.value = token
            userInfo.value = user_Info
            isLogin.value = true
       } else {
        localStorage.clear()
        isLogin.value = false
       }
    }
    /* 存 authorization*/
    function saveAuthorization(auth) {
        authorization.value = auth
        localStorage.setItem("authorization", authorization.value)
    }
    /* 存userinfo */
    function saveUserInfo(user){
        userInfo.value = user
        localStorage.setItem("userInfo", JSON.stringify(userInfo.value))
    }

    function outLogin () {
        localStorage.clear()
        setUserStore()
        router.replace("/home")  //退出直接replace
        Message({type: "warn" ,text: "你已经退出"})
    }
    return {
        authorization, userInfo, saveAuthorization, saveUserInfo, outLogin, isLogin, setUserStore
    }
})